﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Text;
using System.IO;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace CPlase.Internal
{
    public static class RoleCommunicatior
    {
        public const string KEY1_KEY = "key";
        public const string KEY1_VALUE = "key_value";
        public const string KEY2_KEY = "key2";
        public const string KEY2_VALUE = "key_value2";
        public const string MESSAGE_WORKER_QUEUE_HANDLER = "WQH";
        public const string MESSAGE_WORKER_ECHO_HANDLER = "WEH";

        public static bool WebRoleCommand(IRoleEchoCommand Command)
        {
            foreach (RoleInstance roleInst in RoleEnvironment.Roles["CPlaseWebRole"].Instances)
            {

                WebRequest reqPOST = WebRequest.Create(
                    "http://" + roleInst.InstanceEndpoints["InterEndpoint"].IPEndpoint + "/Internal/Command.ashx");
                reqPOST.Method = "POST";
                reqPOST.Timeout = 120000;
                reqPOST.ContentType = "application/x-www-form-urlencoded";

                var Params = new Dictionary<string, string>();

                Params[KEY1_KEY] = KEY1_VALUE;
                Params[KEY2_KEY] = KEY2_VALUE;
                Params["command"] = Command.Command;
                var ExtraParams = Command.Serialize();
                foreach (var ExtraParam in ExtraParams)
                {
                    Params.Add(ExtraParam.Key, ExtraParam.Value);
                }

                string STDIN = "";
                foreach (var Item in Params)
                {
                    STDIN += Item.Key + "=" + HttpUtility.UrlEncode(Item.Value, Encoding.UTF8) + "&";
                }

                byte[] sentData = Encoding.UTF8.GetBytes(STDIN);

                reqPOST.ContentLength = sentData.Length;
                System.IO.Stream sendStream = reqPOST.GetRequestStream();
                sendStream.Write(sentData, 0, sentData.Length);
                sendStream.Close();

                System.Net.WebResponse resp = reqPOST.GetResponse();
                System.IO.Stream stream = resp.GetResponseStream();
                System.IO.StreamReader sr = new StreamReader(stream);
                string s = sr.ReadToEnd();
            }

            return true;
        }

        public static bool WorkerRoleCommand(Type CommandType)
        {
            int InstancesCount = RoleEnvironment.Roles["ServiceWorkerRole"].Instances.Count;
            var roleInst = RoleEnvironment.Roles["ServiceWorkerRole"].Instances[new Random().Next(InstancesCount)];
            WebRequest reqPOST = System.Net.WebRequest.Create("http://" +
                   roleInst.InstanceEndpoints["ServiceEndpoint"].IPEndpoint + "/");
            reqPOST.Method = "POST";
            reqPOST.Timeout = 120000;
            reqPOST.ContentType = "application/x-www-form-urlencoded";

            var Params = new Dictionary<string, string>();

            Params[KEY1_KEY] = KEY1_VALUE;
            Params[KEY2_KEY] = KEY2_VALUE;
            Params["messageType"] = MESSAGE_WORKER_QUEUE_HANDLER;
            Params["queueType"] = CommandType.AssemblyQualifiedName;

            string STDIN = "";
            foreach (var Item in Params)
            {
                STDIN += Item.Key + "=" + HttpUtility.UrlEncode(Item.Value, Encoding.UTF8) + "&";
            }

            byte[] sentData = Encoding.UTF8.GetBytes(STDIN);

            reqPOST.ContentLength = sentData.Length;
            System.IO.Stream sendStream = reqPOST.GetRequestStream();
            sendStream.Write(sentData, 0, sentData.Length);
            sendStream.Close();

            System.Net.WebResponse resp = reqPOST.GetResponse();
            System.IO.Stream stream = resp.GetResponseStream();
            System.IO.StreamReader sr = new StreamReader(stream);
            string s = sr.ReadToEnd();

            return true;
        }

        public static bool WorkerRoleEchoCommand(IRoleEchoCommand Command)
        {
            foreach (RoleInstance roleInst in RoleEnvironment.Roles["ServiceWorkerRole"].Instances)
            {

                WebRequest reqPOST = System.Net.WebRequest.Create("http://" +
                    roleInst.InstanceEndpoints["ServiceEndpoint"].IPEndpoint + "/");
                reqPOST.Method = "POST";
                reqPOST.Timeout = 120000;
                reqPOST.ContentType = "application/x-www-form-urlencoded";

                var Params = new Dictionary<string, string>();

                Params[KEY1_KEY] = KEY1_VALUE;
                Params[KEY2_KEY] = KEY2_VALUE;
                Params["command"] = Command.Command;
                Params["messageType"] = MESSAGE_WORKER_ECHO_HANDLER;
                var ExtraParams = Command.Serialize();
                foreach (var ExtraParam in ExtraParams)
                {
                    Params.Add(ExtraParam.Key, ExtraParam.Value);
                }

                string STDIN = "";
                foreach (var Item in Params)
                {
                    STDIN += Item.Key + "=" + HttpUtility.UrlEncode(Item.Value, Encoding.UTF8) + "&";
                }

                byte[] sentData = Encoding.UTF8.GetBytes(STDIN);

                reqPOST.ContentLength = sentData.Length;
                System.IO.Stream sendStream = reqPOST.GetRequestStream();
                sendStream.Write(sentData, 0, sentData.Length);
                sendStream.Close();

                System.Net.WebResponse resp = reqPOST.GetResponse();
                System.IO.Stream stream = resp.GetResponseStream();
                System.IO.StreamReader sr = new StreamReader(stream);
                string s = sr.ReadToEnd();
            }

            return true;
        }

    }
}